const express = require('express')
const app = express()

const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))

const cors = require('cors')
app.use(cors())

app.use(express.static('./pages'))


const privateKey = '123'
var jwt = require('jsonwebtoken');  //  加密
var expressJWT = require('express-jwt');//  解密


//  会解密 解密后会将用户信息存储到req.user中
/* 有api不需要校验token ，没有api的需要校验token  */
app.use(expressJWT({
    secret: privateKey
}).unless({ path: [/^\/api\//] }));



// var session = require("express-session");
// app.use(session({
//     secret: 'keyboard cat',
//     resave: false,
//     saveUninitialized: true
// }))



app.post('/api/login', (req, res) => {
    if (req.body.username !== 'admin' || req.body.password !== '123456') {
        res.send({
            code: 0,
            msg: '用户信息不对'
        })
    }
    /* 生成token */
    var token = jwt.sign({ usernmae: req.body.username }, privateKey, { expiresIn: '15s' });
    res.send({
        code: 1,
        msg: '登录成功',
        token
    })
})

app.post('/username', (req, res) => {
    console.log(req.user, 66665555)

    res.send({
        code: 1,
        msg: 'username'
    })
})


app.get('/api/logout', (req, res) => {
    
    // req.session.destroy()
    res.send({
        code: 1,
        msg: '退出登录成功'
    })
})

app.use(( err,req,res,next)=>{
   console.log(err.name,777777)
   if(err.name=='UnauthorizedError'){
       res.send({
           msg:'token失效请重新登录获取'
       })
   }

   res.send('服务器异常')
})


app.listen(2000, () => {
    console.log('服务器:http://127.0.0.1:2000')
})